package com.hw.paltfrom.service.casemain;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hw.paltfrom.exception.HWSystemException;
import com.hw.paltfrom.mapper.HwBaseAnnexesfileMapper;
import com.hw.paltfrom.mapper.HwCaseMainMapper;
import com.hw.paltfrom.mapper.HwCasePoliceoperMapper;
import com.hw.paltfrom.pack.ResponseResult;
import com.hw.paltfrom.pojo.HwBaseAnnexesfile;
import com.hw.paltfrom.pojo.HwBaseWorkflow;
import com.hw.paltfrom.pojo.HwCaseMain;
import com.hw.paltfrom.pojo.HwCasePoliceoper;
import com.hw.paltfrom.pojo.HwCommandWorkflow;
import com.hw.paltfrom.rescode.HWSystemCode;
import com.hw.paltfrom.service.doncutor.BaseWorkflowService;
import com.hw.paltfrom.service.doncutor.CommandWorkflowService;
import com.hw.paltfrom.utils.ExportExcelUtil;
import com.hw.paltfrom.utils.RandomNumberUtil;
import com.hw.paltfrom.utils.ResponeResultUtil;
import com.hw.paltfrom.vo.HWcaseMainexportVo;
import com.hw.paltfrom.vo.PoliceCasemainFileVo;
import com.hw.paltfrom.vo.PoliceCasemainVo;

@Service
public class PoliceCasemainServer {

	@Autowired
	private HwCaseMainMapper caseMainMapper;
	@Autowired
	private HwCasePoliceoperMapper policeoperMapper;
	@Autowired
	private HwBaseAnnexesfileMapper annexesfileMapper;

	@Autowired //// 创建基础工作流的接口
	private BaseWorkflowService baseWorkflowService;

	@Autowired
	private CommandWorkflowService commandWorkflowService;

	public Map<String, Object> query(PoliceCasemainVo vo) {

		Integer pageNum = vo.getPageNum();
		Integer pageSize = vo.getPageSize();

		// // 办理阶段
		// String F_AJ_CrtStep = vo.getF_AJ_CrtStep();
		//
		String F_AJ_Police = vo.getF_AJ_Police();
		// 车牌号
		String F_CL_TruckNo = vo.getF_CL_TruckNo();
		// 轴数
		String F_CL_Axis = vo.getF_CL_Axis();
		// 超限吨数
		String F_CL_OverWeight = vo.getF_CL_OverWeight();
		// 静态检测开始时间
		Timestamp StartTime = null;
		// 静态检测结束时间
		Timestamp EndTime = null;
		// 驾驶员
		String F_DriverName = vo.getF_DriverName();
		// 驾驶证号
		String F_DriverCode = vo.getF_DriverCode();
		String F_AreaCode = vo.getF_AreaCode();
		String F_OverrunName = vo.getF_OverrunName();
		String compare = vo.getCompare();
		PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
		if (vo.getStartTime() == null) {
			if (vo.getEndTime() == null) {
			} else {
				return ResponseResult.fail(HWSystemCode.PARAMS_ERROR);
			}
		} else {
			if (vo.getEndTime() != null) {
				StartTime = Timestamp.valueOf(vo.getStartTime());
				EndTime = Timestamp.valueOf(vo.getEndTime());
			} else {
				return ResponseResult.fail(HWSystemCode.PARAMS_ERROR);
			}
		}

		Wrapper<HwCaseMain> mainEntity = new EntityWrapper<HwCaseMain>();
		if (StringUtils.isNotBlank(F_AJ_Police)) {
			if (F_AJ_Police.equals("0")) {
				mainEntity.eq("F_AJ_CrtStep", "04").eq("F_AJ_Police", "0");
			} else {
				mainEntity.eq("F_AJ_Police", "1");
			}
		}

		if (StringUtils.isNotBlank(F_CL_TruckNo)) {
			mainEntity.like("F_CL_TruckNo", F_CL_TruckNo);

		}
		if (StringUtils.isNotBlank(F_CL_Axis)) {
			mainEntity.eq("F_CL_Axis", F_CL_Axis);
		}

		if (F_CL_OverWeight != null) {
			switch (compare) {
			case "1":
				mainEntity.ge("F_CL_OverWeight", F_CL_OverWeight);
				break;
			case "0":
				mainEntity.eq("F_CL_OverWeight", F_CL_OverWeight);
				break;
			case "-1":
				mainEntity.le("F_CL_OverWeight", F_CL_OverWeight);
				break;
			}
		}

		if (StringUtils.isNotBlank(F_DriverName)) {
			mainEntity.like("F_DriverName", F_DriverName);
		}
		if (StartTime != null && EndTime != null) {
			mainEntity.between("F_CL_CheckTime", StartTime, EndTime);

		}
		if (StringUtils.isNotBlank(F_DriverCode)) {
			mainEntity.like("F_DriverCode", F_DriverCode);
		}
		if (StringUtils.isNotBlank(F_AreaCode)) {
			mainEntity.like("F_AreaCode", F_AreaCode);
		}
		if (StringUtils.isNotBlank(F_OverrunName)) {
			mainEntity.like("F_OverrunName", F_OverrunName);
		}

		List<HwCaseMain> mainList = caseMainMapper.selectList(mainEntity);

		PageInfo<HwCaseMain> info = new PageInfo<HwCaseMain>(mainList);
		return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS, info);
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class,
			HWSystemException.class })
	public Map<String, Object> handle(PoliceCasemainFileVo vo) {

		String userid = vo.getUserid();
		String username = vo.getUsername();

		String F_CaseId = vo.getFcaseid();
		String F_OverrunID = vo.getFoverrunid();
		// 被处罚人（默认绑定HW_Case_Main.F_DriverName）
		String F_PunishUserName = vo.getFpunishusername();
		// 联系方式（默认绑定HW_Case_Main.F_DriverPhone）
		String F_PunishUserPhone = vo.getFpunishuserphone();
		// 处罚结果（罚款计分；暂扣机动车驾驶证；吊销机动车驾驶证）
		String F_PunishResult = vo.getFpunishresult();
		// 处罚结果描述、
		String F_PunishRemak = vo.getFpunishremak();
		// 记分及罚款（下拉选择:不记分不罚款|3分300元|6分1000元|6分1500元|6分2000元，数据库数据分开存：罚款金额、记分字段）、
		String F_PunishScore = vo.getFpunishscore();
		String F_PunishAmount = vo.getFpunishamount();
		// // 行政处罚决定书附件GUID
		String F_PunishFile = vo.getFpunishfile();
		
		String code = RandomNumberUtil.getNumber();

		// 判断是否已经办理
		HwCaseMain oldCase = caseMainMapper.selectById(F_CaseId);
		Integer ajPolice = oldCase.getfAjPolice();
		if (ajPolice == 1) {
			ResponeResultUtil.fail(HWSystemCode.FAIL);
		}

		// 更新案件主表
		Wrapper<HwCaseMain> mainEntity = new EntityWrapper<HwCaseMain>();
		mainEntity.eq("F_CaseId", F_CaseId);

		HwCaseMain entity = new HwCaseMain();
		entity.setfAjPolice(1);
		entity.setfAjPoliceamount(Integer.parseInt(F_PunishAmount));
		entity.setfAjPolicescore(Integer.parseInt(F_PunishScore));
		Integer update = caseMainMapper.update(entity, mainEntity);
		if (update != 1) {
			return ResponeResultUtil.fail(HWSystemCode.IS_PUNISH);
		}

		Wrapper<HwCasePoliceoper> policEntity = new EntityWrapper<HwCasePoliceoper>();
		policEntity.eq("F_MainId", F_CaseId);
		policEntity.eq("F_OverrunID", F_OverrunID);

		HwCasePoliceoper polic = new HwCasePoliceoper();
		polic.setfPunishusername(F_PunishUserName);
		polic.setfPunishuserphone(F_PunishUserPhone);
		polic.setfPunishremak(F_PunishRemak);
		polic.setfPunishresult(F_PunishResult);
		polic.setfPunishamount(Integer.parseInt(F_PunishAmount));
		polic.setfPunishscore(Integer.parseInt(F_PunishScore));
//		polic.setfPunishfile(F_PunishFile);
		polic.setfPunishfile(code);
		polic.setfPunishdatetime(new Timestamp(System.currentTimeMillis()));
		polic.setfAccount(userid);
		polic.setfAccountname(username);

		Integer PiloicUpdate = policeoperMapper.update(polic, policEntity);
		if (PiloicUpdate != 1) {
			throw new HWSystemException();
		}
		//
		ArrayList<HwBaseAnnexesfile> fileList = vo.getFileList();
		
		
//		附件 
		for (HwBaseAnnexesfile file : fileList) {
			file.setFileId(RandomNumberUtil.getNumber());
			file.setfFolderid(code);
			file.setfCreatedate(new Timestamp(System.currentTimeMillis()));
			annexesfileMapper.insert(file);
		}

		// 插入流程
		String getfAjCrtstep = oldCase.getfAjCrtstep();
		String flowCode = oldCase.getFlowCode();
		HwBaseWorkflow presentWorkflow = baseWorkflowService.getPresentWorkflow(getfAjCrtstep, flowCode);

		// 创建各阶段审批操作过程
		HwCommandWorkflow hwCommandWorkflow = new HwCommandWorkflow();
		hwCommandWorkflow.setCommandworkflowId(RandomNumberUtil.getNumber());
		hwCommandWorkflow.setWorkflowModule(presentWorkflow.getWorkflowModule());
		hwCommandWorkflow.setWorkflowType(flowCode);
		hwCommandWorkflow.setWorkflowCode(getfAjCrtstep);
		hwCommandWorkflow.setWorkflowCodename(presentWorkflow.getWorkflowCodename());
		hwCommandWorkflow.setCommandworkflowButtonname(vo.getButtonName());
		hwCommandWorkflow.setfAccount(vo.getUseracount());
		hwCommandWorkflow.setfFromdepcode(vo.getFfromdepcode());
		hwCommandWorkflow.setfFromdepname(vo.getFfromdepname());
		hwCommandWorkflow.setCommandworkflowDatatime(new Date());
		hwCommandWorkflow.setCommandworkflowContent(vo.getFpunishremak());
		hwCommandWorkflow.setfAnnexes(code);
		// hwCommandWorkflow.setCommandworkflowContent(vo.getTaskContent());
		hwCommandWorkflow.setObjectId(F_CaseId);// 有什么用字段
		
//		20191124更新写死
//		hwCommandWorkflow.setWorkflowNextcode(presentWorkflow.getWorkflowNextcode());
//		hwCommandWorkflow.setWorkflowNextcodename(presentWorkflow.getWorkflowNextcodename());
		hwCommandWorkflow.setWorkflowNextcode("99");
		// (4.2)各审批操作过程表，插入内容：全部，对应异地复检处理
		// 向各阶段审批操作过程表插入数据
		boolean success = commandWorkflowService.addWorkflow(hwCommandWorkflow);
		if (success == false) {
			// 事务回滚
			throw new HWSystemException();
		}

		return ResponeResultUtil.success(HWSystemCode.SUCCESS);
	}

	public Map<String, Object> onlyQuery(PoliceCasemainVo vo) {

		Integer pageNum = vo.getPageNum();
		Integer pageSize = vo.getPageSize();

		// // 办理阶段
		// String F_AJ_CrtStep = vo.getF_AJ_CrtStep();
		//
		// String F_AJ_Police = vo.getF_AJ_Police();
		// 车牌号
		String F_CL_TruckNo = vo.getF_CL_TruckNo();
		// 轴数
		String F_CL_Axis = vo.getF_CL_Axis();
		// 超限吨数
		Double F_CL_OverWeight = null;
		if (StringUtils.isNotBlank(vo.getF_CL_OverWeight())) {
			F_CL_OverWeight = Double.parseDouble(vo.getF_CL_OverWeight());
		}

		// 静态检测开始时间
		Timestamp StartTime = null;
		// 静态检测结束时间
		Timestamp EndTime = null;
		// 驾驶员
		String F_DriverName = vo.getF_DriverName();
		// 驾驶证号
		String F_DriverCode = vo.getF_DriverCode();

		String startMoney = vo.getStartMoney();
		String endMoney = vo.getEndMoney();
		String F_AreaCode = vo.getF_AreaCode();
		// String F_OverrunName = vo.getF_OverrunName();
		String F_OverrunCode = vo.getFoverruncode();
		String compare = vo.getCompare();
		if (vo.getStartTime() == null) {
			if (vo.getEndTime() == null) {
			} else {
				return ResponseResult.fail(HWSystemCode.PARAMS_ERROR);
			}
		} else {
			if (vo.getEndTime() != null) {
				StartTime = Timestamp.valueOf(vo.getStartTime());
				EndTime = Timestamp.valueOf(vo.getEndTime());
			} else {
				return ResponseResult.fail(HWSystemCode.PARAMS_ERROR);
			}
		}

		Wrapper<HwCaseMain> mainEntity = new EntityWrapper<HwCaseMain>();
		// if (StringUtils.isNotBlank(F_AJ_Police)) {
		// if (F_AJ_Police.equals("0")) {
		// mainEntity.eq("F_AJ_CrtStep", "04").eq("F_AJ_Police", "0");
		// } else {
		// mainEntity.eq("F_AJ_Police", "1");
		// }
		// }
		mainEntity.ne("F_AJ_CrtStep", "01");

		if (StringUtils.isNotBlank(startMoney) && StringUtils.isNotBlank(endMoney)) {
			mainEntity.between("F_AJ_PoliceAmount", startMoney, endMoney);
		}

		if (StringUtils.isNotBlank(F_CL_TruckNo)) {
			mainEntity.like("F_CL_TruckNo", F_CL_TruckNo);

		}
		if (StringUtils.isNotBlank(F_CL_Axis)) {
			mainEntity.eq("F_CL_Axis", F_CL_Axis);
		}

		if (F_CL_OverWeight != null) {
			switch (compare) {
			case "1":
				mainEntity.ge("F_CL_OverWeight", F_CL_OverWeight);
				break;
			case "0":
				mainEntity.eq("F_CL_OverWeight", F_CL_OverWeight);
				break;
			case "-1":
				mainEntity.le("F_CL_OverWeight", F_CL_OverWeight);
				break;
			}
		}

		if (StringUtils.isNotBlank(F_DriverName)) {
			mainEntity.like("F_DriverName", F_DriverName);
		}
		if (StartTime != null && EndTime != null) {
			mainEntity.between("F_CL_CheckTime", StartTime, EndTime);

		}
		if (StringUtils.isNotBlank(F_DriverCode)) {
			mainEntity.like("F_DriverCode", F_DriverCode);
		}
		if (StringUtils.isNotBlank(F_AreaCode)) {
			mainEntity.eq("F_AreaCode", F_AreaCode);
		}
		// if (StringUtils.isNotBlank(F_OverrunName)) {
		// mainEntity.like("F_OverrunName", F_OverrunName);
		// }
		if (StringUtils.isNotBlank(F_OverrunCode)) {
			mainEntity.like("F_OverrunCode", F_OverrunCode);
		}
		PageHelper.startPage(pageNum, pageSize);
		List<HwCaseMain> mainList = caseMainMapper.selectList(mainEntity);

		PageInfo<HwCaseMain> info = new PageInfo<HwCaseMain>(mainList);
		return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS, info);
	}

	public Map<String, Object> Export(PoliceCasemainVo vo) {

		Integer pageNum = vo.getPageNum();
		Integer pageSize = vo.getPageSize();

		// // 办理阶段
		// String F_AJ_CrtStep = vo.getF_AJ_CrtStep();
		//
		String F_AJ_Police = vo.getF_AJ_Police();
		// 车牌号
		String F_CL_TruckNo = vo.getF_CL_TruckNo();
		// 轴数
		String F_CL_Axis = vo.getF_CL_Axis();
		// 超限吨数
		String F_CL_OverWeight = vo.getF_CL_OverWeight();
		// 静态检测开始时间
		Timestamp StartTime = null;
		// 静态检测结束时间
		Timestamp EndTime = null;
		// 驾驶员
		String F_DriverName = vo.getF_DriverName();
		// 驾驶证号
		String F_DriverCode = vo.getF_DriverCode();
		String F_AreaCode = vo.getF_AreaCode();
		String F_OverrunName = vo.getF_OverrunName();
		String compare = vo.getCompare();
		if (vo.getStartTime() == null) {
			if (vo.getEndTime() == null) {
			} else {
				return ResponseResult.fail(HWSystemCode.PARAMS_ERROR);
			}
		} else {
			if (vo.getEndTime() != null) {
				StartTime = Timestamp.valueOf(vo.getStartTime());
				EndTime = Timestamp.valueOf(vo.getEndTime());
			} else {
				return ResponseResult.fail(HWSystemCode.PARAMS_ERROR);
			}
		}

		Wrapper<HwCaseMain> mainEntity = new EntityWrapper<HwCaseMain>();
		if (StringUtils.isNotBlank(F_AJ_Police)) {
			if (F_AJ_Police.equals("0")) {
				mainEntity.eq("F_AJ_CrtStep", "04").eq("F_AJ_Police", "0");
			} else {
				mainEntity.eq("F_AJ_Police", "1");
			}
		}

		if (StringUtils.isNotBlank(F_CL_TruckNo)) {
			mainEntity.like("F_CL_TruckNo", F_CL_TruckNo);

		}
		if (StringUtils.isNotBlank(F_CL_Axis)) {
			mainEntity.eq("F_CL_Axis", F_CL_Axis);
		}

		if (F_CL_OverWeight != null) {
			switch (compare) {
			case "1":
				mainEntity.ge("F_CL_OverWeight", F_CL_OverWeight);
				break;
			case "0":
				mainEntity.eq("F_CL_OverWeight", F_CL_OverWeight);
				break;
			case "-1":
				mainEntity.le("F_CL_OverWeight", F_CL_OverWeight);
				break;
			}
		}

		if (StringUtils.isNotBlank(F_DriverName)) {
			mainEntity.like("F_DriverName", F_DriverName);
		}
		if (StartTime != null && EndTime != null) {
			mainEntity.between("F_CL_CheckTime", StartTime, EndTime);

		}
		if (StringUtils.isNotBlank(F_DriverCode)) {
			mainEntity.like("F_DriverCode", F_DriverCode);
		}
		if (StringUtils.isNotBlank(F_AreaCode)) {
			mainEntity.like("F_AreaCode", F_AreaCode);
		}
		if (StringUtils.isNotBlank(F_OverrunName)) {
			mainEntity.like("F_OverrunName", F_OverrunName);
		}
		PageHelper.startPage(pageNum, pageSize);
		List<HwCaseMain> mainList = caseMainMapper.selectList(mainEntity);
		PageInfo<HwCaseMain> info = new PageInfo<HwCaseMain>(mainList);
		List<HwCaseMain> list = info.getList();

		String jsonString = JSONArray.toJSONString(list);
		JSONArray parseArray = JSON.parseArray(jsonString);
		List<HWcaseMainexportVo> exportData = JSON.parseObject(parseArray.toJSONString(),
				new TypeReference<List<HWcaseMainexportVo>>() {
				});

		ExportExcelUtil<HWcaseMainexportVo> util = new ExportExcelUtil<HWcaseMainexportVo>();
		String[] heads = { "超限站", "车牌号", "轴数", "静态称重", "超限吨数", "静态检测时间", "驾驶员", "驾驶证号", "处罚金额", "记分"};
		String exportExcel = util.exportExcel(exportData,heads, ExportExcelUtil.EXCEL_FILE_2003);
		return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS, exportExcel);
	}
}
